package org.e_gold.factory.crawler;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.e_gold.dao.CountryDAO;
import org.e_gold.dao.LeagueDAO;
import org.e_gold.model.crawler.livescore.CEvent;
import org.e_gold.model.crawler.livescore.Country;
import org.e_gold.model.crawler.livescore.League;
import org.e_gold.service.CEventService;
import org.e_gold.service.CountryService;
import org.e_gold.service.LeagueService;
import org.e_gold.util.DateUtil;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author Thang Nguyen
 */
@Component
@Scope("singleton")
public class LiveScoreCrawlerThread extends Thread{

	private static final Logger logger = Logger.getLogger(LiveScoreCrawlerThread.class);

	@Autowired
	private CountryDAO countryDAO;

	@Autowired
	private CountryService countryService;

	@Autowired
	private LeagueDAO leagueDAO;

	@Autowired
	private LeagueService leagueService;

	@Autowired
	private CEventService cEventService;

	private final String LIVE_SOCCER_URL = "http://www.livescore.com/";

	@Override
	public void run() {
		try{
			while(true){
				try{
					logger.info("<<<<<<<<<<<<Live Score Crwaler has started>>>>>>>>>>>> ");
					export();
					logger.info("<<<<<<<<<<<<Live Score Crwaler has done>>>>>>>>>>>> ");
					Thread.sleep(5 * 60 * 1000);
				}catch(Exception ex){
					logger.info("Internet problem???: " + ex.getMessage());
					logger.error(ex);
					ex.printStackTrace();
				}
			}
		}catch(Exception ex){
			logger.info("<<<<<<<<<<<<Live Score Crwaler has stopped>>>>>>>>>>>> " + ex.getMessage());
			logger.error(ex);
			ex.printStackTrace();
		}
	}

	public void export() {
		try {
			Connection connection = Jsoup.connect(LIVE_SOCCER_URL).timeout(60 * 1000);
			Document doc = connection.get();
			Elements contents = doc.getElementsByClass("content");
			Elements docLeague = contents.first().getElementsByClass("league-table");
			System.out.printf("<<<found : %s >>>\r\n", docLeague.size());

			//get all League & Country
			List<Element> lstLeague = docLeague.subList(0, docLeague.size());

			//traveling all element
			for(Element el : lstLeague){
				try{
					//get useful info
					Elements rows = el.getElementsByTag("tr");
					if(rows.size() > 1){	//only process if rows more than 1 line
						String countryHref = "";
						String countryName = "";
						String leagueName = "";
						String homeName = "";
						String guestName = "";
						List<CEvent> lstCEvent = new ArrayList<CEvent>();					

						//---------------first row is country, league, date
						Element cEventInfo = rows.subList(0, 1).get(0);
						//get country and league span
						Elements eCountryAndDate = cEventInfo.getElementsByTag("span");
						Element eCountry = eCountryAndDate.first();
						Element eDate = eCountryAndDate.last();
						//parsing date
						String strDate = eDate.text();
						strDate = StringUtils.trim(strDate) + " 2014";
						Date play_date = DateUtil.getDateByPattern("MMM dd yyyy", strDate);

						//get link tag contains
						Elements eCountryNLeague = eCountry.getElementsByTag("a");

						//get info and assign to entity
						countryHref = eCountryNLeague.first().attr("href");
						countryName = eCountryNLeague.first().text();
						leagueName = eCountryNLeague.last().text();

						//----------persist country & League
						Country country = countryService.getCountryPersisted(new Country(countryName, countryHref));
						League league = leagueService.getLeaguePersisted(new League(leagueName, country));

						//get Event list
						List<Element> lstCEventElement = rows.subList(1, rows.size());
						for(Element eCEvent : lstCEventElement){
							if(eCEvent.getElementsByClass("fh").size() == 0){
								continue;
							}
							homeName = eCEvent.getElementsByClass("fh").first().text();
							guestName = eCEvent.getElementsByClass("fa").first().text();

							CEvent cEvent = new CEvent();
							cEvent.setHomeName(homeName);
							cEvent.setAwayName(guestName);
							cEvent.setLeague(league);
							cEvent.setPlay_date(play_date);
							lstCEvent.add(cEvent);
						}
						cEventService.saveEvent(lstCEvent);
					}
				}catch(Exception ex){
					logger.info("Error parsing: " + el);
					ex.printStackTrace();
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		LiveScoreCrawlerThread lThread = new LiveScoreCrawlerThread();
		lThread.export();
	}
}
